<?php

namespace App\Admin\Renderable;

use App\Models\Administrator;
use App\Models\Clue;
use App\Models\Tag;
use Carbon\Carbon;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SetClueTagForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     *
     * @param array $input
     * @return \Dcat\Admin\Http\JsonResponse
     */
    public function handle(array $input)
    {
        // id转化为数组
        $id = data_get($this->payload, 'id') ?? explode(',', $input['id'] ?? null);
        if (!$id) return $this->response()->error('参数错误');

        $tagId = $input['tag_id'];


        if (!$tagId || !$tag = Tag::find($tagId))
            return $this->response()->error('分配错误的标签!');

        $clues = Clue::query()
            ->select([
                'id',
                'tag_id',
            ])
            ->whereIn('id', (array)$id)
            ->get();

        foreach ($clues as $clue) {
            if ($clue->tag_id === $tag->id)
                continue;
            $clue->tag_id = $tag->id;
            $clue->save();
        }

        return $this->response()->success('设置标签成功')->refresh();
    }

    public function form()
    {

//        $items = Administrator::getDispatchUserList();
        $this->select('tag_id', '标签')
            ->options(Tag::toOptions());


        $this->hidden('id')->attribute('id', 'order-status-id');
    }

    public function default()
    {
        return [
            'tag_id' => data_get($this->payload, 'tag_id')
        ];
    }
}
